<script lang="ts" setup>
import type { ButtonOnChooseavatar } from '@uni-helper/uni-app-types'
import { useUploadFile } from '@/common/composables/useUpload'
import { IconPath, OperateList, PagePath, PageTitle } from '@/common/constants'
import { HttpStatusCodes } from '@/common/enum/http-status-codes'
import { getUserInfoByIdService, getUserOperatesByRoleService, loginAdminService, loginWeChatService } from '@/common/service/users'
import { useUserStore } from '@/common/store'
import type { OperateItem } from '@/common/types/user'

const { contentAreaHeight, tabBarHeight } = useLayoutInfo()

/**
 * userStore
 */
const { hope_user_info, setUserInfo, clearUserInfo, setToken, hope_token } = useUserStore()

/**
 * 登录参数
 */
const loginParams = ref({
  code: '',
  nickname: '',
  avatarUrl: 'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132',
})
/**
 * popup ref
 */
const popupRef = ref()

// 使用 useUploadFile 组合式函数上传文件
const { uploadFile } = useUploadFile()

/**
 * 打开popup
 */
const openPopup = () => {
  popupRef.value.open()
}

/**
 * 选择头像事件
 * @param e
 */
const onChooseAvatar: ButtonOnChooseavatar = (e) => {
  uni.downloadFile({
    url: e.detail.avatarUrl,
    success: async (res) => {
      if (res.statusCode === HttpStatusCodes.OK) {
        const tempFilePath = res.tempFilePath
        // 上传用户头像
        const url = await uploadFile(tempFilePath)
        loginParams.value.avatarUrl = url
      }
    },
  })
}

const isLoading = ref(false)

/**
 * 获取用户信息
 */
const getUserInfoById = async () => {
  isLoading.value = true
  const { data } = await getUserInfoByIdService()

  setUserInfo(data)

  isLoading.value = false
}

/**
 * 微信授权登录
 */
const loginWeChat = async () => {
  // TODO: 用户填充昵称无法获取值的问题
  console.log(loginParams.value.nickname)

  if (loginParams.value.nickname.trim().length === 0) {
    return uni.showToast({
      title: '昵称不能为空',
      icon: 'none',
    })
  }

  if (loginParams.value.nickname.includes(' ')) {
    return uni.showToast({
      title: '昵称不能包含空格',
      icon: 'none',
    })
  }

  uni.login({
    provider: 'weixin',
    success: async (success) => {
      // 获取code
      loginParams.value.code = success.code
      // 微信授权登录
      const { data } = await loginWeChatService(loginParams.value)

      // 将token存储到本地中
      setToken(data)
      console.log(data)

      // 获取用户信息
      await getUserInfoById()
      // 本地存储用户信息
      uni.showToast({
        icon: 'none',
        title: '授权登录成功',
      })

      // 刷新页面
      uni.reLaunch({
        url: PagePath.MY,
      })
    },
    fail: (err) => {
      uni.showToast({
        icon: 'none',
        title: '授权登录失败',
      })
      console.log(err)
    },
    complete: () => {
      // 关闭popup
      popupRef.value.close()
    },
  })
}

/** 退出登录 */
const loginOut = () => {
  uni.showModal({
    title: '温馨提示',
    content: '您确定要退出登录吗?',
    success: (success) => {
      if (success.confirm) {
        // 退出登录
        clearUserInfo()

        uni.reLaunch({
          url: PagePath.HOME,
        })
      }
    },
  })
}

/**
 * 一键登录管理员账号
 */
const onLoginAdmin = async () => {
  const { data } = await loginAdminService()
  // 存储token
  setToken(data)
  console.log(data)

  await getUserInfoById()

  uni.showToast({
    icon: 'none',
    title: '管理员一键登录成功',
  })

  // 刷新页面
  uni.reLaunch({
    url: PagePath.MY,
  })
}

/** 计算用户操作列表 */
// const operateList = computed(() => {
//   return hope_user_info?.role === UserRole.USER ? OperateList : AdminOperateList
// })

const operateList = ref<OperateItem[]>(OperateList)

/** 获取当前用户的操作项 */
const getUserOperate = async () => {
  const { data } = await getUserOperatesByRoleService()
  operateList.value = data
}

onLoad(async () => {
  if (hope_token) {
    await getUserInfoById()
  }
})

onShow(() => {
  // 获取 拦截路由时 本地存储的isToLogin
  const isToLogin = uni.getStorageSync('isToLogin')
  if (isToLogin) {
    // 等待dom渲染完毕
    nextTick(() => openPopup())
  }

  uni.removeStorageSync('isToLogin')

  // 获取当前用户的操作项
  getUserOperate()
})
</script>

<template>
  <!-- 自定义头部导航栏组件 -->
  <hope-nav-bar :title="PageTitle.MY" />
  <scroll-view
    scroll-y :style="{
      height: `${contentAreaHeight - tabBarHeight}px`,
    }"
  >
    <view class="my-container">
      <view class="user-card">
        <!-- 用户卡片组件 -->
        <hope-user-card
          :nickname="hope_user_info?.nickname" :avatar-url="hope_user_info?.avatarUrl"
          :points="hope_user_info?.points || 0"
        />
      </view>

      <!-- 用户操作项列表 -->
      <view class="my-operate">
        <view v-for="item in operateList" :key="item.id">
          <hope-user-operate-item :operate-item="item" name="每日签到" @on-click="() => goToPage(item.path)" />
        </view>
        <view v-if="!hope_token" class="my-operate-login" @click="openPopup">
          一键登录
        </view>

        <view v-else class="my-operate-login" @click="loginOut">
          退出登录
        </view>
      </view>
    </view>
  </scroll-view>

  <uni-popup ref="popupRef" type="bottom" background-color="#ffffff">
    <view class="popup-container">
      <view class="popup-header">
        <uni-section title="信息" type="line" title-font-size="36rpx" />
        <image class="popup-close" :src="IconPath.DELETE" mode="scaleToFill" @click="() => popupRef.close()" />
      </view>
      <view class="popup-avatar popup-item">
        <text class="popup-label">
          头像:
        </text>
        <button
          plain class="popup-avatar-button" type="default" open-type="chooseAvatar"
          style="border: none;margin: 0;padding: 0;" @chooseavatar="onChooseAvatar"
        >
          <image class="popup-avatar-img" :src="loginParams.avatarUrl" mode="aspectFit" />
        </button>
      </view>

      <view class="popup-nickname popup-item">
        <text class="popup-label">
          用户名:
        </text>
        <input
          :value="loginParams.nickname" type="nickname" class="popup-nickname-text" placeholder="请输入您的昵称"
          @confirm="(e) => {
            console.log(e)
          }"
          @input="(e) => {
            loginParams.nickname = e.detail.value
          }"
        >
      </view>
    </view>

    <view class="popup-button">
      <view @click="loginWeChat">
        <hope-button title="确认授权登录" />
      </view>
      <view @click="onLoginAdmin">
        <hope-button title="管理员测试账号一键登录" />
      </view>
    </view>
  </uni-popup>
</template>

<style scoped lang="scss">
.user-card {
  padding-inline: 30rpx;
  margin-top: 60rpx;
}

.my {
  &-container {
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  &-operate {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 50rpx;
    margin-top: 60rpx;
    padding: $border-radius-base;
    background-color: $color-white;
    border-top-left-radius: $border-radius-base;
    border-top-right-radius: $border-radius-base;

    &-login {

      height: 150rpx;
      text-align: center;
      line-height: 150rpx;
      border-radius: $border-radius-base;
      background-color: $color-primary;
      font-size: $font-size-lg;
      color: $color-white;
    }
  }
}

.popup {
  &-container {
    display: flex;
    flex-direction: column;
    padding: $padding-base;
  }

  &-close {
    height: 35rpx;
    width: 35rpx;
  }

  &-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  &-label {
    width: 200rpx;
    font-size: $font-size-base;
  }

  &-item {
    display: flex;
    align-items: center;
    margin-top: 30rpx;

  }

  &-avatar {
    flex: 1;

    &-button {
      display: flex;
      align-items: center;
    }

    &-img {
      width: 120rpx;
      height: 120rpx;
      border-radius: 50%;
    }

  }

  &-nickname {
    flex: 1;

    &-text {
      padding: $padding-base;
      flex: 1;
    }
  }

  &-button {
    display: flex;
    flex-direction: column;
    gap: $padding-base;
    padding: $padding-base;
  }
}
</style>
)
